package UTIL;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadUtil {
	// private static final long serialVersionUID = 1L;

	private DiskFileItemFactory fileUpload = new DiskFileItemFactory();
	private ServletFileUpload sfu = new ServletFileUpload(fileUpload);

	private String diretorio = "arquivos";
	private String filename;

	private static int KB = 1024;
	private static int MB = 1024 * 1024;
	private int size = 1;
	private String extensoesPermitidas = "jpg, gif, png";
	
	private byte[] img;

	private String erro = null;

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public String getErro() {
		return erro;
	}

	public void setErro(String erro) {
		this.erro = erro;
	}

	public String getDiretorio() {
		return diretorio;
	}

	public String getFilename() {
		return filename;
	}

	public String getExtensoesPermitidas() {
		return extensoesPermitidas;
	}

	public void setExtensoesPermitidas(String extensoesPermitidas) {
		this.extensoesPermitidas = extensoesPermitidas;
	}

	public boolean doFilePost(HttpServletRequest request, ServletContext context) {
		if (request.getContentType() == null)
			return false;

		if (!request.getContentType().startsWith("multipart/form-data")) {
			setErro("Seu formulário não envia aplicativos");
			return false;
		}

		fileUpload.setSizeThreshold(4 * KB);

		String path = context.getRealPath(getDiretorio());
		try {
			sfu.setSizeMax(getSize() * MB);

			List list = sfu.parseRequest(request);

			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				FileItem item = (FileItem) iterator.next();

				if (!item.isFormField()) {
					filename = item.getName();

					if ((filename != null) && (!filename.equals(""))) {
						filename = (new File(filename)).getName();
						if (isPermission(filename)) {
							item.write(new File(path + "/" + filename));
							img = item.get();
						} else {
							setErro("Arquivo não permitido");
							return false;
						}
					}
				}
			}

		} catch (FileUploadBase.SizeLimitExceededException slee) {
			slee.printStackTrace();
			setErro("Tamanho excedido");
			return false;
		} catch (Exception e) {
			setErro("Uma exceção ocorreu" + e.getMessage());
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public void setDiretorio(String diretorio) {
		this.diretorio = diretorio;
	}

	public boolean isPermission(String fileName) {
		String lowerCaseName = fileName.toLowerCase();
		StringTokenizer st = new StringTokenizer(extensoesPermitidas, " ,");

		while (st.hasMoreElements()) {
			if (lowerCaseName.endsWith("." + st.nextToken()))
				return true;
		}

		return false;
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadUtil() {
		super();
		
		setDiretorio("img");
		setSize(1);
		setExtensoesPermitidas("jpg, gif, png");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	public byte[] getImg() {
		return img;
	}

	public void setImg(byte[] img) {
		this.img = img;
	}

}
